package me.gavin.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.FragmentManager
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import me.gavin.BR
import me.gavin.ext.behavior
import me.gavin.ext.layoutParams
import me.gavin.util.log

abstract class BaseBottomSheetDialog : BottomSheetDialogFragment() {

    abstract val layoutId: Int

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(layoutId, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        afterCreate(savedInstanceState)
    }

    abstract fun afterCreate(savedInstanceState: Bundle?)

    override fun onStart() {
        super.onStart()
        initBehavior()
    }

    protected open fun initBehavior() {
        (view?.parent as? View)?.apply {
            layoutParams.height = CoordinatorLayout.LayoutParams.MATCH_PARENT
            setBackgroundResource(android.R.color.transparent)
            val behavior = layoutParams<CoordinatorLayout.LayoutParams>()
                .behavior<BottomSheetBehavior<*>>()
                .apply { isHideable = false }
            post { behavior.peekHeight = height }
        }
    }

    fun show(manager: FragmentManager) {
        show(manager, this.javaClass.simpleName.also {
            "show - $it".log()
        })
    }

}

abstract class BindingBottomSheetDialog<B : ViewDataBinding> : BaseBottomSheetDialog() {

    lateinit var binding: B
        private set

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = initDataBinding(inflater, container)
        binding.lifecycleOwner = this
        return binding.root
    }

    protected open fun initDataBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): B {
        return DataBindingUtil.inflate(inflater, layoutId, container, false)
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.unbind()
    }

}

abstract class BindingVMBottomSheetDialog<B : ViewDataBinding> : BindingBottomSheetDialog<B>() {

    abstract val viewModel: BaseViewModel

    override fun initDataBinding(inflater: LayoutInflater, container: ViewGroup?): B {
        return super.initDataBinding(inflater, container).also {
            it.setVariable(BR.vm, viewModel)
        }
    }

}